import os
import re
import polib
import display_name
import configparser

config = configparser.ConfigParser()
config.read(r'C:\Users\jan\Documents\Project\page_py\py\tools\settings.ini')


# 输出当前工作目录
# print(os.getcwd())

en_file = config.get('Paths', 'en_file')
ru_file = config.get('Paths', 'ru_file')
zh_file = config.get('Paths', 'zh_file')
search_path = config.get('Paths','search_path')


def has_chinese_char(text):
    # If the string is empty, ends with a digit, ends with '字符串', or contains '{' or '}', return False
    if not text or text[-1].isdigit() or text.endswith('字符串'):
        return False
    return any('\u4e00' <= char <= '\u9fff' for char in text)




def process_tscn_file(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        contents = file.read()
    pattern = r'"([^"/\\]*[\u4e00-\u9fa5]+[^"/\\]*)"'
    return re.findall(pattern, contents, re.DOTALL)

# def process_tscn_file(filename):
#     with open(filename, 'r', encoding='utf-8') as file:
#         contents = file.read()
#     return re.findall(r'tip|logName|text = "(.*?)"', contents)

# #支持换行符
# def process_tscn_file(filename):
#     with open(filename, 'r', encoding='utf-8') as file:
#         contents = file.read()
#     pattern = re.compile(r"(['\"])(.*?)\1", re.DOTALL)
#     matches = pattern.finditer(contents)
#     return [match.group(2) for match in matches]

def process_gd_file(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        contents = file.read()
    matches = re.finditer(r"(['\"])(.*?)\1", contents)
    return [match.group(2) for match in matches]

features_to_skip = ['func', '/', '\\']
def add_to_po_file(po_filename, entries):
    try:
        po = polib.pofile(po_filename)
        existing_entries = {entry.msgid for entry in po}
        for entry in entries:
            if entry not in existing_entries and has_chinese_char(entry):
                if '{' in entry:
                    # 使用正则表达式提取大括号中的内容
                    result = re.findall(r"\{([^}]+)\}", entry)
                    # 输出提取的内容
                    for item in result:
                        # print(item)#此处会重复
                        po.append(polib.POEntry(msgid=item))
                    continue
                elif any(feature in entry for feature in features_to_skip):
                    continue
                po.append(polib.POEntry(msgid=entry))
        po.save(po_filename)
    except ValueError:
        print(entries)
        print(ValueError)


#去重项
def remove_duplicates_in_po(filename):
    # 读取 .po 文件
    po = polib.pofile(filename)

    seen = {}
    new_po = polib.POFile()
    new_po.metadata = po.metadata  # 复制元数据

    for entry in po:
        # 如果这是一个新的 msgid，把它和对应的 msgstr 保存到字典中，并添加到新的 PO 文件
        if entry.msgid not in seen:
            seen[entry.msgid] = entry.msgstr
            new_po.append(entry)
        else:
            # 如果msgid已经存在，但新的msgstr有值（即非空字符串），我们可以用新的msgstr更新旧的msgstr
            if entry.msgstr != "":
                seen[entry.msgid] = entry.msgstr
                # 找到旧的msgstr并更新它
                for old_entry in new_po:
                    if old_entry.msgid == entry.msgid:
                        old_entry.msgstr = entry.msgstr
                        break

    # 把修改后的 .po 文件保存回磁盘
    new_po.save(filename)


def delete_like_entries(po_file_path):
    # Load the .po file
    po = polib.pofile(po_file_path)

    # Define the entries to remove
    entries_to_remove = []

    # Loop over all entries
    for entry in po:
        # Check if the msgid contains 'function' or looks like code
        if 'function' in entry.msgid:
            entries_to_remove.append(entry)

    # Remove the selected entries
    for entry in entries_to_remove:
        po.remove(entry)

    # Save the .po file
    po.save(po_file_path)


def process_directory(dir, po_filename):
    for root, dirs, files in os.walk(dir):
        print(files)
        for file in files:
            if file.endswith('.tscn'):
                entries = process_tscn_file(os.path.join(root, file))

                add_to_po_file(po_filename, entries)
            elif file.endswith('.gd'):
                if file == 'CNConstants.gd':continue
                entries = process_gd_file(os.path.join(root, file))
                add_to_po_file(po_filename, entries)

    add_to_po_file(po_filename,display_name.values)


process_directory(search_path, ru_file)
process_directory(search_path, en_file)


delete_like_entries(en_file)
delete_like_entries(ru_file)

remove_duplicates_in_po(en_file)
remove_duplicates_in_po(ru_file)
